package com.alm.handle.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 文件处理工具类
 *
 * @author ywy
 */
@Log4j2
public class FileUtil {

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";


    /**
     * 输出指定文件的byte数组(不关闭输出流
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeZipBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 获取系统临时目录
     *
     * @return
     */
    public static String getTemp() {
        return System.getProperty("java.io.tmpdir");
    }

    /**
     * 创建临时文件
     *
     * @param filePath
     * @param data
     * @return
     */
    public static File createTempFile(String filePath, byte[] data) throws IOException {
        String temp = getTemp() + filePath;
        File file = new File(temp);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data, 0, data.length);
        fos.flush();
        fos.close();
        return file;
    }

    /**
     * 文件路径回溯校验(文件名是否包含"./"以及"../")
     *
     * @param path
     * @return
     */
    public static boolean isBacktrack(String path) {
        // 通过使用File.separator 无法过滤windows下的回溯
        return path.contains(".\\") || path.contains("..\\") || path.contains("../") || path.contains("./");
        //return path.contains("." + File.separator) || path.contains(".." + File.separator);
    }

    /**
     * 通过文件地址下载文件并输出为二进制数组
     * @param fileUrl 下载路径
     * @return
     */
    public static byte[] downloadByUrl(String fileUrl) {
        InputStream input = null;
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            input = connection.getInputStream();
            return IOUtils.toByteArray(input);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if(input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 创建文件夹
     * @param folder 文件夹名称
     */
    private File createDirectory(String folder) throws IOException {
        File directory = new File("");
        String courseFile = directory.getCanonicalPath();
        File filePath = new File(courseFile, "/excel/" + folder);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        return filePath;
    }

    /**
     * 创建文件
     * @param filePath 文件父路径
     * @param bytes 文件数据
     * @param suffix 后缀（文件类型）
     * @return
     */
    public String createFile(File filePath, byte[] bytes, String suffix) {
        String file = "";
        try {
            File fileName = new File(filePath.toString(), UUID.randomUUID().toString() + "." + suffix);
            file = fileName.toString();
            FileOutputStream stream = new FileOutputStream(fileName);
            stream.write(bytes);
            stream.flush();
            stream.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
